/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName ApplicationCurrentDomainUpdater.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.application
{
	
	import com.gesturesoft.imultimax.model.AppModel;
	import com.gesturesoft.imultimax.model.DataBaseManager;
	import com.gesturesoft.imultimax.model.application.interfaces.IApplicationUpdater;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.interfaces.IDatabaseManager;
	import com.gesturesoft.imultimax.model.vo.StyleVO;
	
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	import mx.core.FlexGlobals;
	import mx.styles.CSSStyleDeclaration;

	public class ApplicationCurrentDomainUpdater implements IApplicationUpdater
	{
		
		private var query:String;
		private var styleCollection:ArrayCollection;
		private var assetCollection:ArrayCollection;
		private var cssStyle:CSSStyleDeclaration;
		private var _selectedCompany:String;	
		private var _iDatabaseManager:IDatabaseManager;
		private var _themes:ArrayCollection;
		private var _activeThemeDetails:Array;
		
		public function ApplicationCurrentDomainUpdater(value:String)
		{
			
			_iDatabaseManager = new DataBaseManager();
			
			_selectedCompany = value;
			
			var query:String;
			
			
			/*else
			{
				this._themes = new ArrayCollection();
			}*/
			//END:Check for any data in active theme table
			
			//START:Get style detials from db
			query = "SELECT * FROM IM_STYLES WHERE st_company='"+_selectedCompany+"'";
			styleCollection = retrieveHandler(query);
			//END:Get style detials from db
			
			//START:Get asset detials from db and store it to AppModel
			query = "SELECT * FROM IM_ASSETS WHERE as_company='"+_selectedCompany+"'";
			assetCollection = retrieveHandler(query);
			storeAssetValues(assetCollection);
			
			AppModel.getInstance().assets = assetCollection;
			//END:Get asset detials from db
			
			//START:Update startup company
			executeHandler("UPDATE IM_COMPANIES SET cmp_startup='0'");
			executeHandler("UPDATE IM_COMPANIES SET cmp_startup='1' WHERE cmp_company='"+_selectedCompany+"'");
			//END:Update startup company
			
			//START:Getting currency used by the company
			query = "SELECT cmp_currency FROM IM_COMPANIES WHERE cmp_company='"+_selectedCompany+"'";
			var currency:ArrayCollection = retrieveHandler(query);
			if( currency.length > 0)
				AppModel.getInstance().currency = currency[0].cmp_currency;
			else
				AppModel.getInstance().currency = '£';
			//END:Getting currency used by the company
			
		}
		
		public function update():void
		{
			
			var arrThemes:ArrayCollection = new ArrayCollection();
			//START:Check for any theme is active
			//SELECT ref FROM beforelist WHERE name IN (SELECT refer FROM user WHERE statu='ab')
			query = "SELECT * FROM IM_THEME_DETAILS WHERE td_id IN (SELECT th_id FROM IM_THEMES WHERE th_active='true')";
			arrThemes = retrieveHandler( query );
			if( arrThemes.length > 0 )
			{
				
				formatActiveThemeDetails( arrThemes );
				
				//this._themes = arrThemes;
			}
			
			//format style collection 
			//id:get all styles curresponding to a style name
			var formattedStyleArray:Array = formatStyles();
			
			if( this._activeThemeDetails )
			{
				
				//var activePropertyVal:String;
				var activeTablePropery:String;
				var activeTableSubPropery:String;
				
				for each(var arrCol:ArrayCollection in formattedStyleArray)
				{
					var cssStyle:CSSStyleDeclaration = new CSSStyleDeclaration();
					var className:String;
					
					for each(var styleVo:StyleVO in arrCol)
					{
						
						if(!className)
							className = styleVo.className;
						if(styleVo.activeTablePropery)
						{
							cssStyle.setStyle(styleVo.property,_activeThemeDetails[styleVo.activeTablePropery][styleVo.activeTableSubPropery]);
						}
						else
						{
							cssStyle.setStyle(styleVo.property,styleVo.value);
						}
						
					}
					
					FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration(className, cssStyle, true);
					className = null;
					
				}
				
			}
			else
			{
				
				applyTheme(formattedStyleArray);
				
			}
			
			
		}
		
		/**
		 * This is the function for apply theme
		 * 
		 * @functionName applyTheme
		 * @creationDate Sep 5, 2012
		 * @author GestureSoft
		 * @params arg:String
		 */
		private function applyTheme(formattedStyleArray:Array):void
		{
			
			for each(var arrCol2:ArrayCollection in formattedStyleArray)
			{
				var cssStyle2:CSSStyleDeclaration = new CSSStyleDeclaration();
				var className2:String;
				
				for each(var styleVo2:StyleVO in arrCol2)
				{
					
					if(!className2)
						className2 = styleVo2.className;
					cssStyle2.setStyle(styleVo2.property,styleVo2.value);
					
				}
				
				FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration(className2, cssStyle2, true);
				className2 = null;
			}
			
		}
		
		private function formatActiveThemeDetails(arrThemes:ArrayCollection):void
		{
		
			_activeThemeDetails = new Array();
			
			for each( var item:Object in arrThemes )
			{
				
				var obj:Object = new Object;
				
				obj.gradient1  = item.gradient1;
				obj.gradient2  = item.gradient2;
				obj.stroke     = item.stroke;
				obj.values	   = item.value;
				obj.color      = item.text_color;
				
				_activeThemeDetails[item.property_name] = obj;
				
			}
			
		}
		
		private function formatStyles():Array
		{
			
			var formatedArray:Array = new Array();
			
			for each(var item:Object in styleCollection)
			{
				
				if(!formatedArray[item.st_class_name])
				{
					formatedArray[item.st_class_name] = new ArrayCollection();
				}
				
				var styleVo:StyleVO = new StyleVO();
				
				styleVo.className = item.st_class_name;
				styleVo.property = item.st_property;
				styleVo.value = item.st_value;
				styleVo.activeTablePropery = item.st_active_table_propery;
				styleVo.activeTableSubPropery = item.st_active_table_sub_propery;
				
				ArrayCollection( formatedArray[item.st_class_name] ).addItem(styleVo);
			}
			
			return formatedArray;
			
		}
		
		private function storeAssetValues(assetsArray:ArrayCollection):void
		{
			
			var obj:Object = new Object();
			var appModel:AppModel = AppModel.getInstance();
			var backgroundImage:String;
			
			if( this._activeThemeDetails )
			{
				
				for each(var item:Object in assetsArray)
				{
					
					if(item.as_type == "background")
					{
						backgroundImage = _activeThemeDetails[item.as_active_table_propery][item.values];
						obj[item.as_type+item.as_name] = File.applicationStorageDirectory.resolvePath(_selectedCompany+"/"+backgroundImage).url;
					}
					else
					{
						obj[item.as_type+item.as_name] = item.as_value.toString();
					}
					
				}
				
			}
			else
			{
				for each(var item2:Object in assetsArray)
				{
					obj[item2.as_type+item2.as_name] = item2.as_value.toString();
				}
				
			}
			
			AppModel.getInstance().assetObj = obj;
			
		}
		
		private function retrieveHandler(val:String):ArrayCollection
		{
			
			var result:ArrayCollection;
			
			try
			{
				
				result =  _iDatabaseManager.getData(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-retrieveHandler() : Database Read error");
				throw error;
				
			}
			
			return result;
			
		}
		
		private function executeHandler(val:String):void
		{
			
			try
			{
				
				_iDatabaseManager.execute(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("ApplicationStyleUpdator-executeHandler() : Database execution error");
				throw error;
				
			}
			
		}
		
	}
	
}